# coding: utf-8

import sip
import config
import app.tools as tool
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import Qt, SIGNAL
from app.ui.icon import Icon
from app.tools.dialog import MessageBox
from app.ui.tab.tab_page_string import TabPageString
from app.ui.tab.tab_page_hash import TabPageHash
from app.ui.tab.tab_page_list import TabPageList
from app.ui.tab.tab_page_about import TabPageAbout
from app.ui.tab.tab_page_help import TabPageHelp


class Tab(object):

    def __init__(self, parent=None):
        self.icon = Icon()
        self.tab_widget = QtGui.QTabWidget(parent)
        self.tab_widget.setObjectName(tool._from_utf8("tab_widget"))
        self.tab_widget.setElideMode(QtCore.Qt.ElideNone)
        self.tab_widget.setDocumentMode(False)
        self.tab_widget.setMovable(True)
        self.tab_widget.setDocumentMode(True)
        self.tab_widget.setTabsClosable(True)
        self.tab_widget.tabCloseRequested.connect(self.close_tab)
        self.tab_widget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.tab_widget.customContextMenuRequested.connect(self.context_menu)
        self.tab_widget.currentChanged.connect(self.tab_page_change)
        self.add_about()
        self.tab_widget.tabBar().setTabButton(0, QtGui.QTabBar.RightSide, None)

    def get_instance(self):
        return self.tab_widget

    def get_pages(self):
        pages = set()
        page_count = self.count()
        for i in range(0, page_count):
            page = self.get(i)
            pages.add(page)
        return pages

    def tab_page_change(self, index):
        pages = self.get_pages()
        for page in pages:
            if not hasattr(page, 'value'):
                continue
            if not hasattr(page.value, 'timer_stop'):
                continue
            page.value.timer_stop()
        current_page = self.get(index)
        if not hasattr(current_page, 'value'):
            return
        if not hasattr(current_page.value, 'timer_start'):
            return
        current_page.value.timer_start()

    def context_menu(self, pos):
        page_count = self.count()
        if page_count <= 0:
            return
        tab_bar = self.tab_widget.tabBar()
        self.mouse_page_index = tab_bar.tabAt(pos)
        print(page_count)
        print(self.mouse_page_index)
        menu = QtGui.QMenu(self.tab_widget)
        menu.addAction('Close', self.tab_page_close)
        if page_count > 1:
            menu.addAction('CloseAll', self.tab_page_close_all)
            menu.addAction('CloseOther', self.tab_page_close_other)
        if self.mouse_page_index != 0:
            menu.addAction('CloseLeft', self.tab_page_close_left)
        if (self.mouse_page_index + 1) != page_count:
            menu.addAction('CloseRight', self.tab_page_close_right)
        menu.exec_(QtGui.QCursor.pos())

    def tab_page_close(self):
        self.close_tab(self.mouse_page_index)

    def tab_page_close_all(self):
        page_count = self.count()
        if page_count == 0:
            return
        for i in range(page_count, -1, -1):
            self.close_tab(i)

    def tab_page_close_other(self):
        page_count = self.count()
        if page_count == 0:
            return
        current_page = self.get(self.mouse_page_index)
        for i in range(page_count, -1, -1):
            page = self.get(i)
            if not current_page or current_page == page:
                continue
            self.close_tab(i)

    def tab_page_close_left(self):
        page_count = self.count()
        if page_count == 0:
            return
        left_max_index = self.mouse_page_index - 1
        for i in range(left_max_index, -1, -1):
            self.close_tab(i)

    def tab_page_close_right(self):
        page_count = self.count()
        if page_count == 0:
            return
        right_max_index = page_count - 1
        for i in range(right_max_index, self.mouse_page_index, -1):
            self.close_tab(i)

    def size(self):
        return self.tab_widget.size()

    def resize(self, size):
        self.tab_widget.resize(size)
        pages = self.get_pages()
        for page in pages:
            if not page:
                continue
            page.resize(size)

    def get(self, index):
        return self.tab_widget.widget(index)

    def index(self, widget):
        return self.tab_widget.indexOf(widget)

    def count(self):
        return self.tab_widget.count()

    def set_current_index(self, index=0):
        self.tab_widget.setCurrentIndex(index)

    def close_tab(self, index=-1):
        if index == -1:
            index = self.tab_widget.currentIndex()
        if index == -1:
            return
        tab_widget_page = self.get(index)
        if tab_widget_page:
            tab_widget_page.value.close()
        self.tab_widget.removeTab(index)

    def use(self, name):
        tab_widget_page = self.tab_widget.findChild((QtGui.QWidget,), tool._from_utf8(name))
        if tab_widget_page is None:
            return False
        tab_widget_page_index = self.index(tab_widget_page)
        if tab_widget_page_index < 0:
            sip.delete(tab_widget_page)
            return False
        return self.tab_widget.setCurrentIndex(tab_widget_page_index)

    def add(self, item, factory, name):
        if self.use(name) is not False:
            return
        key_type = factory.type(name)
        tab_type = {'string': self._init_string, 'hash': self._init_hash, 'list': self._init_list}
        func = tab_type.get(key_type)
        if not func:
            item.remove()
            MessageBox.info('tips', 'key not found!')
            # raise NotFoundKey('key not found!')
            return
        func(item, factory, name)
        self.set_current_index(self.count() - 1)

    def add_about(self):
        name = 'about'
        if self.use(name) is not False:
            return
        self._init_about(name)
        self.set_current_index(self.count() - 1)

    def add_help(self):
        name = 'help'
        if self.use(name) is not False:
            return
        self._init_help(name)
        self.set_current_index(self.count() - 1)

    def _init_about(self, name):
        tab_page_about = TabPageAbout(self, name)
        tab_page = tab_page_about.get_instance()
        self.tab_widget.addTab(tab_page, tool._from_utf8(name))

    def _init_help(self, name):
        tab_page_help = TabPageHelp(self, name)
        tab_page = tab_page_help.get_instance()
        self.tab_widget.addTab(tab_page, self.icon.get(config.ICON_HELP), tool._from_utf8(name))

    def _init_string(self, item, factory, name):
        tab_page_string = TabPageString(self, item, factory, name)
        tab_page = tab_page_string.get_instance()
        self.tab_widget.addTab(tab_page, self.icon.get(config.ICON_KEY), tool._from_utf8(name))

    def _init_hash(self, item, factory, name):
        tab_page_hash = TabPageHash(self, item, factory, name)
        tab_page = tab_page_hash.get_instance()
        self.tab_widget.addTab(tab_page, self.icon.get(config.ICON_KEY), tool._from_utf8(name))

    def _init_list(self, item, factory, name):
        tab_page_list = TabPageHash(self, item, factory, name)
        tab_page = tab_page_list.get_instance()
        self.tab_widget.addTab(tab_page, self.icon.get(config.ICON_KEY), tool._from_utf8(name))

